/*
 * Copyright (c) 2014 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.business;

import it.polimi.se2.agostini_cantini_dignani.meteocal.entity.Calendar;
import it.polimi.se2.agostini_cantini_dignani.meteocal.entity.Event;
import it.polimi.se2.agostini_cantini_dignani.meteocal.entity.User;

import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Alessandro Cantini
 */
@Stateless
public class CalendarManager {

	private Logger logger = Logger.getLogger(CalendarManager.class.getName());

	@EJB
	private EventManager eventMgr;

	@EJB
	private UserManager um;

	@PersistenceContext
	private EntityManager em;

	public void editCalendar(Calendar calendar) {
		Calendar old = calendar;
		em.merge(calendar);
		old = calendar;
	}

	public InputStream xmlExport(Calendar calendar) {
		InputStream is = null;

		try {
			File file = File.createTempFile("calendar", null);
			JAXBContext context = JAXBContext.newInstance(Calendar.class);
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(calendar, file);
			is = new FileInputStream(file);
		} catch (JAXBException e) {
			logger.log(Level.SEVERE, "Error exporting calendar to XML", e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Error creating temp file", e);
		}

		return is;
	}

	public void xmlImport(Calendar calendar, InputStream is) throws ImportCalendarException {
		if (calendar == null || is == null) {
			throw new IllegalArgumentException("Can't accept null values");
		}

		Calendar newCal;
		try {
			JAXBContext context = JAXBContext.newInstance(Calendar.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			newCal = (Calendar) unmarshaller.unmarshal(is);
		} catch (JAXBException e) {
			logger.warning("Error importing calendar.");
			throw new ImportCalendarException();
		}

		User owner = calendar.getOwner();
		for (Event e : newCal.getEvents()) {
			if (e.getOwner().equals(owner) && !containsSameEvent(calendar, e)) {
				try {
					eventMgr.createEvent(e, owner);
				} catch (EJBException exc) {
					logger.warning("Impossible to save event: " + e);
					throw new ImportCalendarException();
				}
			}
		}
	}

	private boolean containsSameEvent(Calendar calendar, Event event) {
		for (Event e : calendar.getEvents()) {
			if (eventMgr.areTheSame(e, event)) {
				return true;
			}
		}
		return false;
	}

	public class ImportCalendarException extends Exception {
		public ImportCalendarException() {
			super();
		}
	}
}
